package com.arcsoft.arcfacedemo.util.http;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;

import com.arcsoft.arcfacedemo.common.Advertisement;
import com.arcsoft.arcfacedemo.common.Constants;
import com.arcsoft.arcfacedemo.common.Installation;
import com.arcsoft.arcfacedemo.common.LogInfo;
import com.arcsoft.arcfacedemo.messageHandler.MessageSend2Server;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;

public class HttpUtil {

    //本地测试环境
    public static String baseUrl = "http://" + Constants.server.HOST + ":" + Constants.server.SERVER_PORT + "/api/facePaper/";

    private static final String TAG = "httpUtil";

    //HttpURLConnction
    public static void sendHttpRequest(final String address, final HttpCallBackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(4000);
                    connection.setReadTimeout(4000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    //OKHttp
    public static void sendOKHttp(String address, Map params, okhttp3.Callback callback) {
        StringBuffer stringBuffer = new StringBuffer(baseUrl + address);
        Iterator iterator = params.entrySet().iterator();
        if (iterator.hasNext()) {
            stringBuffer.append("?");
            Object element;
            while (iterator.hasNext()) {
                element = iterator.next();
                Map.Entry<String, Object> entry = (Map.Entry) element;
                //过滤value为null，value为null时进行拼接字符串会变成 "null"字符串
                if (entry.getValue() != null) {
                    stringBuffer.append(element).append("&");
                }
                address = stringBuffer.substring(0, stringBuffer.length() - 1);
            }
        } else {
            address = stringBuffer.toString();
        }
        Log.d(TAG, "请求地址：" + address);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(address)
                .build();
        client.newCall(request).enqueue(callback);
    }


    /**
     * 下载文件
     *
     * @param context       上下文对象
     * @param advertisement 广告相关信息
     * @param interCut      是否时插播
     * @param view          视图
     */
    public static void downloadVideo(final Context context, final Advertisement advertisement, final boolean interCut, final View view) {
        final File video = new File(context.getFilesDir(), "video");
        if (!video.exists()) {
            video.mkdirs();
        }

        if (advertisement.getUrl().startsWith("http")) {
            DownloadTask downloadTask1 = new DownloadTask(new DownloadListener() {
                @Override
                public void onProgress(int progress) {
                    Log.d(TAG, advertisement.getName() + "下载进度：" + progress + "%");
                }

                @Override
                public void onSuccess() {
                    if (view != null) {
                        view.setClickable(true);
                    }
                    Log.d(TAG, advertisement.getName() + "下载成功");
                    // 下载成功--添加到播放列表中
                    if (advertisement.getToken() != null && !"".equals(advertisement.getToken())) {
//                    advertisement.setVideoUrl();
                        if (interCut) {
                            //插播的广告

                            Constants.Advert.INTER_CUT_ADVERT_LIST.add(advertisement);
                            String interCutAdvertListStr = Installation.getInterCutAdvertList(context);
                            try {
                                JSONArray interCutAdvertList = new JSONArray();
                                if (!"".equals(interCutAdvertListStr)) {
                                    interCutAdvertList = new JSONArray(interCutAdvertListStr);
                                }
                                interCutAdvertList.put(advertisement);
                                Installation.putInterCutAdvertList(context, interCutAdvertList.toString());
                            } catch (JSONException e) {
                                MessageSend2Server.sendLog(context, new LogInfo("插播广告：" + advertisement.getName() + "JSON解析错误，" + e.getMessage(), "ERROR"));
                                e.printStackTrace();
                            }
                        } else {
                            //普通的广告

                            String advertListStr = Installation.getAdvertList(context);
                            try {
                                JSONArray adverList = new JSONArray();
                                if (!"".equals(advertListStr)) {
                                    adverList = new JSONArray(advertListStr);
                                }
                                boolean isExit = false;

                                Integer deleteIndex = null;
                                if (adverList.length() > 0) {
                                    for (int i = 0; i < adverList.length(); i++) {
                                        JSONObject jsonObject = new JSONObject(String.valueOf(adverList.get(i)));
                                        if (jsonObject.has("token")) {
                                            String token = jsonObject.getString("token");
                                            if (token.equals(advertisement.getToken())) {
                                                isExit = true;
                                                deleteIndex = i;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (!isExit) {
                                    adverList.put(advertisement);
                                    Installation.putAdvertList(context, adverList.toString());
                                    Constants.Advert.ADVERT_LIST.add(advertisement);
                                } else {
                                    if (deleteIndex != null) {
                                        adverList.remove(deleteIndex);
                                        Installation.putAdvertList(context, adverList.toString());
                                    }
                                    MessageSend2Server.sendLog(context, new LogInfo("该广告已经存在，修改数据成功【" + advertisement + "】", "INFO"));
                                }
                            } catch (JSONException e) {
                                MessageSend2Server.sendLog(context, new LogInfo("添加广告失败【" + advertisement + "】", "ERROR"));
                                e.printStackTrace();
                            }
                        }

                    }
                    if (interCut) {
                        MessageSend2Server.sendLog(context, new LogInfo("插播广告：" + advertisement.getName() + "下载成功", "INFO"));
                    } else {
                        MessageSend2Server.sendLog(context, new LogInfo("广告：" + advertisement.getName() + "下载成功", "INFO"));
                    }
                }

                @Override
                public void onFailed() {
                    if (view != null) {
                        view.setClickable(true);
                    }
                    Log.d(TAG, advertisement.getName() + "下载失败");
                    if (interCut) {
                        MessageSend2Server.sendLog(context, new LogInfo("插播广告：" + advertisement.getName() + "下载失败", "ERROR"));
                    } else {
                        MessageSend2Server.sendLog(context, new LogInfo("广告：" + advertisement.getName() + "下载失败", "ERROR"));
                    }
                }

                @Override
                public void onPaused() {
                    Log.d(TAG, advertisement.getName() + "下载暂停");
                }

                @Override
                public void onCanceled() {
                    if (view != null) {
                        view.setClickable(true);
                    }
                    Log.d(TAG, advertisement.getName() + "下载取消");
                }
            });
            downloadTask1.execute(advertisement.getUrl(), video.getPath());
        }
        if (advertisement.getUrl2().startsWith("http")) {
            DownloadTask downloadTask2 = new DownloadTask(new DownloadListener() {
                @Override
                public void onProgress(int progress) {
                    Log.d(TAG, advertisement.getName() + "下载进度：" + progress + "%");
                }

                @Override
                public void onSuccess() {
                    if (view != null) {
                        view.setClickable(true);
                    }
                    Log.d(TAG, advertisement.getName() + "下载成功");
                    // 下载成功--添加到播放列表中
                    if (advertisement.getToken() != null && !"".equals(advertisement.getToken())) {
//                    advertisement.setVideoUrl();
                        if (interCut) {
                            //插播的广告

                            Constants.Advert.INTER_CUT_ADVERT_LIST.add(advertisement);
                            String interCutAdvertListStr = Installation.getInterCutAdvertList(context);
                            try {
                                JSONArray interCutAdvertList = new JSONArray();
                                if (!"".equals(interCutAdvertListStr)) {
                                    interCutAdvertList = new JSONArray(interCutAdvertListStr);
                                }
                                interCutAdvertList.put(advertisement);
                                Installation.putInterCutAdvertList(context, interCutAdvertList.toString());
                            } catch (JSONException e) {
                                MessageSend2Server.sendLog(context, new LogInfo("插播广告：" + advertisement.getName() + "JSON解析错误，" + e.getMessage(), "ERROR"));
                                e.printStackTrace();
                            }
                        } else {
                            //普通的广告

                            String advertListStr = Installation.getAdvertList(context);
                            try {
                                JSONArray adverList = new JSONArray();
                                if (!"".equals(advertListStr)) {
                                    adverList = new JSONArray(advertListStr);
                                }
                                boolean isExit = false;
                                if (adverList.length() > 0) {
                                    for (int i = 0; i < adverList.length(); i++) {
                                        JSONObject jsonObject = new JSONObject(String.valueOf(adverList.get(i)));
                                        if (jsonObject.has("token")) {
                                            String token = jsonObject.getString("token");
                                            if (token.equals(advertisement.getToken())) {
                                                isExit = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (!isExit) {
                                    adverList.put(advertisement);
                                    Installation.putAdvertList(context, adverList.toString());
                                    Constants.Advert.ADVERT_LIST.add(advertisement);
                                } else {
                                    MessageSend2Server.sendLog(context, new LogInfo("该广告已经存在，不可重复下发【" + advertisement + "】", "ERROR"));
                                }
                            } catch (JSONException e) {
                                MessageSend2Server.sendLog(context, new LogInfo("添加广告失败【" + advertisement + "】", "ERROR"));
                                e.printStackTrace();
                            }
                        }

                    }
                    if (interCut) {
                        MessageSend2Server.sendLog(context, new LogInfo("插播广告：" + advertisement.getName() + "下载成功", "INFO"));
                    } else {
                        MessageSend2Server.sendLog(context, new LogInfo("广告：" + advertisement.getName() + "下载成功", "INFO"));
                    }
                }

                @Override
                public void onFailed() {
                    if (view != null) {
                        view.setClickable(true);
                    }
                    Log.d(TAG, advertisement.getName() + "下载失败");
                    if (interCut) {
                        MessageSend2Server.sendLog(context, new LogInfo("插播广告：" + advertisement.getName() + "下载失败", "ERROR"));
                    } else {
                        MessageSend2Server.sendLog(context, new LogInfo("广告：" + advertisement.getName() + "下载失败", "ERROR"));
                    }
                }

                @Override
                public void onPaused() {
                    Log.d(TAG, advertisement.getName() + "下载暂停");
                }

                @Override
                public void onCanceled() {
                    if (view != null) {
                        view.setClickable(true);
                    }
                    Log.d(TAG, advertisement.getName() + "下载取消");
                }
            });
            downloadTask2.execute(advertisement.getUrl2(), video.getPath());
        }


    }


    /**
     * 下载文件
     *
     * @param context       上下文对象
     * @param advertisement 广告相关信息
     * @param interCut      是否时插播
     * @param view          视图
     */
    public static void downloadImages(final Context context, final Advertisement advertisement, final boolean interCut, final View view) {
        final File imagesFile = new File(context.getFilesDir(), "images");
        if (!imagesFile.exists()) {
            imagesFile.mkdirs();
        }
        Log.e(TAG, "下载banner");
        Log.e(TAG, advertisement.getImages());
        if (advertisement.getImagesFilePath() != null && advertisement.getImagesFilePath().size() > 0) {
            advertisement.getImagesFilePath().clear();
        }
        final String images = advertisement.getImages();

        if (images != null && !"".equals(images)) {
            String[] split = images.split(";");
            for (final String s : split) {
                if (!"".equals(s)) {
                    DownloadTask downloadTask = new DownloadTask(new DownloadListener() {
                        @Override
                        public void onProgress(int progress) {
                            Log.d(TAG, advertisement.getName() + "banner下载进度：" + progress + "%");
                        }

                        @Override
                        public void onSuccess() {
                            if (view != null) {
                                view.setClickable(true);
                            }
                            Log.d(TAG, advertisement.getName() + "banner下载成功");
                            List<String> imagesFilePath = advertisement.getImagesFilePath();
                            if (imagesFilePath == null) {
                                imagesFilePath = new ArrayList<>();
                            }
                            String fileName = s.substring(s.lastIndexOf("/") == -1 ? 0 : s.lastIndexOf("/")).substring(1);
                            Log.e(TAG, "添加banner ：" + fileName);
                            imagesFilePath.add(imagesFile.getPath() + "/" + fileName);
                            advertisement.setImagesFilePath(imagesFilePath);
                        }

                        @Override
                        public void onFailed() {
                            if (view != null) {
                                view.setClickable(true);
                            }
                            Log.d(TAG, advertisement.getName() + "banner下载失败");
                            if (interCut) {
                                MessageSend2Server.sendLog(context, new LogInfo("插播广告banner：" + advertisement.getName() + "下载失败", "ERROR"));
                            } else {
                                MessageSend2Server.sendLog(context, new LogInfo("广告banner：" + advertisement.getName() + "下载失败", "ERROR"));
                            }
                        }

                        @Override
                        public void onPaused() {
                            Log.d(TAG, advertisement.getName() + "banner下载暂停");
                        }

                        @Override
                        public void onCanceled() {
                            if (view != null) {
                                view.setClickable(true);
                            }
                            Log.d(TAG, advertisement.getName() + "banner下载取消");
                        }
                    });
                    //开始下载
                    downloadTask.execute(s, imagesFile.getPath());
                }

            }
        }
    }

    /**
     * 下载安装包
     *
     * @param context 上下文对象
     * @param url     下载地址
     */
    public static void downloadApk(final Context context, final String url, final String versionName) {
        final File apk = new File(context.getFilesDir(), "apk");
        final String fileName = url.substring(url.lastIndexOf("/"));
        if (!apk.exists()) {
            apk.mkdirs();
        }
        DownloadTask downloadTask = new DownloadTask(new DownloadListener() {
            @Override
            public void onProgress(int progress) {
                Log.d(TAG, "APK下载进度：" + progress + "%");
            }

            @Override
            public void onSuccess() {

                Log.d(TAG, "APK下载成功-准备安装");
                // 下载成功--添加到播放列表中
                installApk(context, new File(apk, fileName));
                MessageSend2Server.sendLog(context, new LogInfo("APK下载成功,正在安装", "INFO"));
                Constants.Config.VERSION_CODE = versionName;
            }

            @Override
            public void onFailed() {
                Log.d(TAG, "APK下载失败");
            }

            @Override
            public void onPaused() {
                Log.d(TAG, "APK下载暂停");
            }

            @Override
            public void onCanceled() {
                Log.d(TAG, "APK下载取消");
            }
        });

        downloadTask.execute("http://" + Constants.server.HOST + ":" + Constants.server.SERVER_PORT + url, apk.getPath());
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    protected static boolean isHasInstallPermissionWithO(Context context) {
        if (context == null) {
            return false;
        }
        return context.getPackageManager().canRequestPackageInstalls();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    protected static void startInstallPermissionSettingActivity(Context context) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent();
        //获取当前apk包URI，并设置到intent中（这一步设置，可让“未知应用权限设置界面”只显示当前应用的设置项）
        Uri packageURI = Uri.parse("package:" + context.getPackageName());
        intent.setData(packageURI);
        //设置不同版本跳转未知应用的动作
        if (Build.VERSION.SDK_INT >= 26) {
            //intent = new Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
            intent.setAction(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        } else {
            intent.setAction(android.provider.Settings.ACTION_SECURITY_SETTINGS);
        }
        context.startActivity(intent);
    }

    protected static void installApk(Context context, File apkFile) {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean hasInstallPermission = isHasInstallPermissionWithO(context);
            if (!hasInstallPermission) {
                startInstallPermissionSettingActivity(context);
                return;
            }
        }
        Uri uri = null;
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 24) {//7.0 Android N
            //com.xxx.xxx.fileprovider为上述manifest中provider所配置相同
            uri = FileProvider.getUriForFile(context, "com.arcsoft.arcfacedemo.provider", apkFile);
            intent.setAction(Intent.ACTION_INSTALL_PACKAGE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//7.0以后，系统要求授予临时uri读取权限，安装完毕以后，系统会自动收回权限，该过程没有用户交互
        } else {//7.0以下
            uri = Uri.fromFile(apkFile);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

}